import java.util.List;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;

import weka.classifiers.functions.LibSVM;
import weka.classifiers.Classifier;
import weka.core.Instances;
import algorithms.AWE;
import algorithms.SVM;
import evaluation.Measure;
import util.Utils;

public class Main {

	private static String[] paras = null;

	public static void main(String[] args) throws Exception{

		if(args.length == 0){
		  usage();
		  System.exit(0);
		}
		
		Main.paras = args;
		
		String list = null;
		String models = null;
		String save = null;

		if(args.length > 0){
		  models = getopt("-l");
		  list = getopt("-d");
		  save = getopt("-s");
		}

		Instances[] datasets = getdatasets(list);
		
		LibSVM learner = new LibSVM();
		AWE awe = new AWE(datasets, learner);
		
		if(models != null){
			BufferedReader reader = new BufferedReader(new FileReader(models));
			while(reader.ready()){
			  String model = reader.readLine();	
			  Classifier x = SVM.loadModel(model);
			  awe.addClassifier(x);
			  System.out.println("Classifier Added");
			}
			reader.close();
		}
		
		awe.setMaxEnsembleSize(5);
		awe.setNumberOfFolds(5);
		awe.process();
		awe.information();

// Use getClassifier to save the model external space
//		Classifier cls = awe.getClassifier(0);
//		weka.core.SerializationHelper.write(model, cls);
//		System.out.println("Model Saved");
		
		Measure mea = new Measure(datasets[datasets.length-1]);
		mea.evaluate(awe);
		
		// Save to a directory
		if(save != null){
		  if(!save.endsWith("/"))
		    save=save+"/";	   
			for(int i=0; i<datasets.length;++i){
			  String save_model = save+"aModel"+i+".model";
			  Classifier cls = awe.getClassifier(i);
			  weka.core.SerializationHelper.write(save_model, cls);
			  System.out.println("One Model Saved");
			}
		}
		
	}
	
	private static Instances[] getdatasets(String list) throws Exception{
		BufferedReader reader = new BufferedReader(new FileReader(list));
		List<String> files = new ArrayList<String>();
		while(reader.ready()){
			String line = reader.readLine();
			if(!line.startsWith("#")){
			  files.add(line);
			}
		}
		reader.close();
		Instances[] datasets = new Instances[files.size()];
		for(int i = 0; i < files.size(); ++i){
			datasets[i] = Utils.getInstances(files.get(i)); 
		}
		return datasets;
	}
	
	private static String getopt(String opt){
	  for(int i = 0; i < paras.length; ++i){
	 	if(paras[i].equals(opt))
		  return paras[i+1];
	  }	  

	  return null;	
	}

	private static void usage(){
		System.out.println("ocm -l model -d datasets");
		System.out.println("	Use -l to load a model");
		System.out.println("	Use -d to lcate datasets");
		System.out.println("	Use -s to save all the base learners");
	}
	
	
}
